from http.server import BaseHTTPRequestHandler, HTTPServer
import json
from urllib.parse import urlparse

# 模拟数据库
users = [
    {"id": 1, "name": "用户1", "email": "user1@example.com", "age": 30},
    {"id": 2, "name": "用户2", "email": "user2@example.com", "age": 25}
]
next_user_id = 3

class SimpleAPIHandler(BaseHTTPRequestHandler):
    def _set_headers(self, status_code=200):
        self.send_response(status_code)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

    def do_GET(self):
        parsed_path = urlparse(self.path)
        if parsed_path.path == '/users':
            self._set_headers(200)
            self.wfile.write(json.dumps(users).encode('utf-8'))
        else:
            self._set_headers(404)
            self.wfile.write(json.dumps({"error": "端点未找到"}).encode('utf-8'))

    def do_POST(self):
        parsed_path = urlparse(self.path)
        if parsed_path.path == '/users':
            content_length = int(self.headers['Content-Length'])
            post_data = json.loads(self.rfile.read(content_length).decode('utf-8'))

            global next_user_id
            new_user = {
                "id": next_user_id,
                "name": post_data.get("name", ""),
                "email": post_data.get("email", ""),
                "age": post_data.get("age", 0)
            }
            users.append(new_user)
            next_user_id += 1

            self._set_headers(201)
            self.wfile.write(json.dumps(new_user).encode('utf-8'))
        else:
            self._set_headers(404)
            self.wfile.write(json.dumps({"error": "端点未找到"}).encode('utf-8'))

def run_server():
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, SimpleAPIHandler)
    print(f"启动模拟API服务器在 http://localhost:8000")
    httpd.serve_forever()

if __name__ == '__main__':
    run_server()